/*
 * Copyright (C), 2002-2017, 苏宁易购电子商务有限公司
 * FileName: AdminActivityServiceImpl.java
 * Author:   15060460
 * Date:     2017年4月6日 下午4:14:29
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.sawp.member.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.reflect.TypeToken;
import com.suning.framework.lang2.exception.BizzException;
import com.suning.sawp.constants.CacheKeyConstants;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.intf.dao.IndexCardTaskDaoService;
import com.suning.sawp.intf.store.StoreInfoService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.member.constant.MemberConstants;
import com.suning.sawp.member.dao.ActivityDao;
import com.suning.sawp.member.dao.AdminActivityDao;
import com.suning.sawp.member.dto.Activity;
import com.suning.sawp.member.dto.ActivityStore;
import com.suning.sawp.member.dto.AdminActivity;
import com.suning.sawp.member.service.AdminActivityService;
import com.suning.sawp.member.vo.ActivityStoreListVo;
import com.suning.sawp.member.vo.ActivityStoreVo;
import com.suning.sawp.member.vo.AdminActivityVo;
import com.suning.sawp.member.vo.CustomerDetailVo;
import com.suning.sawp.member.vo.CustomerDetailWithSaleVo;
import com.suning.sawp.member.vo.GridViewVo;
import com.suning.sawp.po.bi.BIIndexTaskCardEntity;
import com.suning.sawp.po.store.StoreInfo;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.RedisCacheUtils;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 15060460
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class AdminActivityServiceImpl implements AdminActivityService {

	@Autowired
	private AdminActivityDao adminActivityDao;

	@Resource
	IndexCardTaskDaoService indexCardTaskDaoService;

	@Resource
	StoreManService storeManService;

	@Autowired
	private ActivityDao activityDao;

	@Autowired
	private StoreInfoService storeInfoService;

	@Autowired
	private RedisCacheUtils redisClient;

	/**
	 * 换行分隔符
	 */
	private static final String LINE_SEPARATOR = "\\n";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.suning.sawp.member.service.AdminActivityService#queryActivityList
	 * (java.lang.String, java.lang.String, int, java.lang.String)
	 */
	@Override
	public GridViewVo<AdminActivity> queryActivityList(String code, String role, Long pageNo, Long pageSize) {
		GridViewVo<AdminActivity> gridView = new GridViewVo<AdminActivity>();
		Long count = adminActivityDao.queryActivitysCount(code, role);
		gridView.setCount(count);
		if (count > 0) {
			List<AdminActivity> activitys;
			if (pageNo == null) {// 没有分页条件
				activitys = adminActivityDao.queryActivitys(code, role, null, null);
				pageNo = 1l;
				pageSize = count;
			} else {
				activitys = adminActivityDao.queryActivitys(code, role, (pageNo - 1) * pageSize, pageSize);
			}
			handleTimeAndStatus(activitys);
			gridView.setData(activitys);
		}
		gridView.setPageNo(pageNo);
		gridView.setPageSize(pageSize);
		return gridView;
	}

	private void handleTimeAndStatus(List<AdminActivity> activitys) {
		for (AdminActivity adminActivity : activitys) {
			if (StringUtils.isNotEmpty(adminActivity.getStartTime()) && StringUtils.isNotEmpty(adminActivity.getEndTime())) {
				Date start = DateUtils.getDateByStr(adminActivity.getStartTime());
				Date end = DateUtils.getDateByStr(adminActivity.getEndTime());
				Date now = new Date();
				String status;
				if (start.after(now)) {// 未开始
					status = MemberConstants.ActivityStatus.NOT_START.getStatus();
				} else if (end.before(now)) {// 已结束
					status = MemberConstants.ActivityStatus.ENDING.getStatus();
				} else {// 进行中
					status = MemberConstants.ActivityStatus.STARTING.getStatus();
				}
				adminActivity.setStatus(status);
				SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DEFAULT_DATE_PATTERN);
				adminActivity.setStartTime(sdf.format(start));
				adminActivity.setEndTime(sdf.format(end));
			}
		}

	}

	@Override
	public List<AdminActivity> queryActivityList(String storeCode, String staffId) {
		List<AdminActivity> activitys = null;
		if (StringUtils.isEmpty(staffId)) {// 店长
			activitys = adminActivityDao.queryActivitysDz(storeCode);
		} else {
			activitys = adminActivityDao.queryActivitysDd(storeCode, staffId);
		}
		if (activitys != null) {
			handleTimeAndStatus(activitys);
		}
		return activitys;
	}

	@Override
	public AdminActivityVo queryActivity(String activityId) {
		Activity activity = activityDao.selectActivityInfoById(activityId);
		AdminActivityVo vo = new AdminActivityVo();
		vo.setId(activityId);
		vo.setName(activity.getName());
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DEFAULT_DATE_PATTERN);
		vo.setStartTime(sdf.format(activity.getStartTime()));
		vo.setEndTime(sdf.format(activity.getEndTime()));
		vo.setCreateUser(activity.getCreateUser());
		vo.setFlow(activity.getFlow());
		List<ActivityStoreVo> storeVos = new ArrayList<ActivityStoreVo>();
		List<ActivityStore> stores = activityDao.queryActivityStoresByActivityId(Long.valueOf(activityId));
		for (ActivityStore activityStore : stores) {
			ActivityStoreVo storeVo = new ActivityStoreVo();
			storeVo.setActivityStoreId(activityStore.getId().toString());
			storeVo.setStoreCode(activityStore.getStoreCode());
			storeVo.setStoreName(activityStore.getStoreName());
			storeVo.setTargetAmount(activityStore.getTargetAmount().toString());
			storeVos.add(storeVo);
		}
		vo.setStores(storeVos);
		return vo;
	}

	/**
	 * 修改活动（大区，分公司）
	 */
	@Override
	@Transactional
	public void modifyActivity(AdminActivityVo adminActivityVo, String staffId) {
		// 首先查询，检查是否能修改
		// 修改活动表
		// 修改活动门店关联表
		String activityId = adminActivityVo.getId();
		Activity activity = activityDao.selectActivityInfoById(activityId);
		List<ActivityStore> delStores = new ArrayList<ActivityStore>();
		checkCanModify(activity, adminActivityVo, delStores);
		// 删除关联门店 活动品类、拓展任务，员工表数据
		for (ActivityStore actStore : delStores) {
			this.adminActivityDao.deleteActStoreAssociatedData(actStore.getActivityId(), actStore.getStoreCode());
		}
		Activity modifyAct = new Activity();
		modifyAct.setName(adminActivityVo.getName());
		modifyAct.setStartTime(DateUtils.getDateByStr(adminActivityVo.getStartTime()));
		modifyAct.setEndTime(DateUtils.getDateByStr(adminActivityVo.getEndTime()));
		modifyAct.setId(Long.valueOf(activityId));
		modifyAct.setUpdateUser(staffId);
		modifyAct.setUpdateTime(new Date());
		// 修改活动表
		activityDao.updateActivity(modifyAct);
		// 批量删除活动门店关联表数据
		adminActivityDao.deleteActivityStore(activityId);
		// 新增活动门店关联表
		List<ActivityStoreVo> storeVos = adminActivityVo.getStores();
		List<ActivityStore> activityStores = new ArrayList<ActivityStore>();
		for (ActivityStoreVo storeVo : storeVos) {
			ActivityStore activityStore = new ActivityStore();
			activityStore.setTargetAmount(new BigDecimal(storeVo.getTargetAmount()));
			activityStore.setStoreCode(storeVo.getStoreCode());
			activityStore.setStoreName(storeVo.getStoreName());
			activityStore.setActivityId(Long.valueOf(activityId));
			activityStores.add(activityStore);
			// 检查门店活动数量
			checkStoreActNum(storeVo);
			delActivityKey(storeVo.getStoreCode());
		}
		// 批量插入
		activityDao.batchSaveActivityStores(activityStores);
	}

	/**
	 * 活动开始时间未在当前时间之后则不能修改
	 *
	 * @param startTime
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private void checkCanModify(Activity activity, AdminActivityVo activityVo, List<ActivityStore> delStores) {
		Date start = activity.getStartTime();
		Date now = new Date();
		if (start.before(now)) {// 进行中or结束
			throw new BizzException("活动已开始，不能修改");
		}
		List<ActivityStore> nowStores = this.activityDao.queryActivityStoresByActivityId(activity.getId());
		List<ActivityStoreVo> modStores = activityVo.getStores();
		// 找出要删除关联的门店,检查是否有拓展客户
		for (ActivityStore as : nowStores) {
			boolean isDel = true;
			for (ActivityStoreVo asVo : modStores) {
				if (as.getStoreCode().equals(asVo.getStoreCode())) {
					isDel = false;
					break;
				}
			}
			if (isDel) {
				Long customers = this.adminActivityDao.countStoreCustomer(as.getActivityId(), as.getStoreCode());
				if (customers > 0) {
					throw new BizzException("门店" + as.getStoreName() + " 已经有拓展人数");
				}
				delStores.add(as);
			}
		}

	}

	/**
	 * 新增活动
	 *
	 * @param adminActivityVo
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@Transactional
	@Override
	public String addActivity(AdminActivityVo adminActivityVo, EmployeeInfo employee) {
		Activity activity = new Activity();
		activity.setName(adminActivityVo.getName());
		activity.setCompanyCode(employee.getBranchCode());
		activity.setCreateTime(new Date());
		activity.setCreateUser(employee.getStaffId());
		activity.setAreaCode(employee.getRegion5Code());
		activity.setCreateUserName(employee.getStaffName());
		activity.setStartTime(DateUtils.getDateByStr(adminActivityVo.getStartTime()));
		activity.setEndTime(DateUtils.getDateByStr(adminActivityVo.getEndTime()));
		if (StringUtils.equals(employee.getOrgLevel(), MemberConstants.EmployeeOrgLevel.CAMPANY)) {
			activity.setCreatorRole(MemberConstants.ONE);// 分公司
		} else if (StringUtils.equals(employee.getOrgLevel(), MemberConstants.EmployeeOrgLevel.AREA)) {// 大区
			activity.setCreatorRole(MemberConstants.ZERO);//
		} else {
			throw new BizzException("权限不足");// 后台大区和分公司才能创建活动
		}
		activity.setFlow(MemberConstants.ZERO);
		activityDao.saveActivity(activity);
		Long activityId = activity.getId();
		// 增加活动门店关联表数据
		// 新增活动门店关联表
		List<ActivityStoreVo> storeVos = adminActivityVo.getStores();
		List<ActivityStore> activityStores = new ArrayList<ActivityStore>();
		// 店长工号集合
		List<String> storeKeppers = new ArrayList<String>();
		for (ActivityStoreVo storeVo : storeVos) {
			ActivityStore activityStore = new ActivityStore();
			activityStore.setTargetAmount(new BigDecimal(storeVo.getTargetAmount()));
			activityStore.setStoreCode(storeVo.getStoreCode());
			activityStore.setStoreName(storeVo.getStoreName());
			activityStore.setActivityId(activityId);
			activityStores.add(activityStore);
			// 检查门店活动数量
			checkStoreActNum(storeVo);
			// 根据门店编码找店长
			List<com.suning.nsfuaa.employee.dto.EmployeeInfo> eList = storeManService.getClerksInStoretiByStoreCd(storeVo.getStoreCode(), ClerkConstants.STORE_KEEPER);
			for (com.suning.nsfuaa.employee.dto.EmployeeInfo e : eList) {
				storeKeppers.add(e.getEmployeeId());
			}
			delActivityKey(storeVo.getStoreCode());
		}
		// 批量插入
		activityDao.batchSaveActivityStores(activityStores);
		// 任务卡片 保存
		saveToTaskCard(storeKeppers);

		return String.valueOf(activityId);
	}

	/**
	 * 一个门店当月活动最多只有10个
	 *
	 * @param storeVo
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	private void checkStoreActNum(ActivityStoreVo storeVo) {
		Long actNums = this.countStoreActivity(storeVo.getStoreCode());
		if (actNums >= 10) {// 一个门店当月只能创建10个活动
			throw new BizzException(storeVo.getStoreName() + "门店活动数量不能大于10个");
		}
	}

	/**
	 * 门店外拓的卡片任务提醒
	 * 
	 * @param employees
	 *            //待提醒的员工
	 */
	private void saveToTaskCard(List<String> employees) {
		if (CollectionUtils.isEmpty(employees)) {
			return;
		}
		for (String employeeId : employees) {
			// 设置首页卡片展示
			BIIndexTaskCardEntity entity = new BIIndexTaskCardEntity();
			// 门店月度销售
			entity.setBizKey(BIIndexTaskCardEntity.BizKey.STORE_EXPAND);
			// 卡片类型
			entity.setCardType(BIIndexTaskCardEntity.CardType.CARD_002);
			// 任务卡片分配的人员
			entity.setStaffId(employeeId);
			// 任务卡片开始时间 用当前时间
			entity.setStartTime(new Date());
			// 任务结束结束时间 开始时间往后推三天
			entity.setEndTime(DateUtils.getNextDay(new Date(), 2));
			// 卡片提示
			entity.setTaskTips(BIIndexTaskCardEntity.Content.STORE_EXPAND_CONTENT);
			// 卡片标题
			entity.setTitle(BIIndexTaskCardEntity.Title.STORE_EXPAND);
			indexCardTaskDaoService.upsertIndexTaskCard(entity);
		}
	}

	@Override
	public ActivityStoreListVo queryStoreList(EmployeeInfo employee, String realShopType) {
		List<StoreInfo> stores;
		if (StringUtils.equals(employee.getOrgLevel(), OrgInfo.ORG_LEVEL.COMPANY_LEVEL)) {// 分公司
			// employee.getBranchCode() 是4位编码
			stores = adminActivityDao.queryStoresBySaleBranchCode(employee.getBranchCode(), realShopType);

			// 走mongo的老方法，没有按门店分类，不用了
			/*
			 * stores =
			 * storeInfoService.queryStoresByBranchCode(employee.getBranchCode
			 * (), StoreInfo.ORG_TYPE.SALE_TYPE)
			 */
		} else if (employee.getOrgLevel().equals(OrgInfo.ORG_LEVEL.REGION_LEVEL)) {// 大区
			stores = adminActivityDao.queryStoresByRegionCode(employee.getRegionCode(), realShopType);

			// 走mongo的老方法，没有按门店分类，不用了
			// stores =
			// storeInfoService.queryStoresByRegionCode(employee.getRegionCode());
		} else {
			throw new BizzException(employee.getOrgLevel() + ",权限不足");
		}
		ActivityStoreListVo listVo = new ActivityStoreListVo();
		if (CollectionUtils.isNotEmpty(stores)) {// 从门店中获取当前大区信息
			StoreInfo store = stores.get(0);
			listVo.setAreaCode(store.getRegionCode());
			listVo.setAreaName(store.getRegionName());
			List<ActivityStoreVo> storeVos = new ArrayList<ActivityStoreVo>();
			for (StoreInfo storeInfo : stores) {
				ActivityStoreVo vo = new ActivityStoreVo();
				vo.setStoreCode(storeInfo.getStoreCode());
				vo.setStoreName(storeInfo.getStoreName());
				storeVos.add(vo);
			}
			listVo.setStores(storeVos);
		}
		return listVo;
	}

	/**
	 * 
	 * 查询某门店当月创建活动的数量 copy自ActivityServiceImpl
	 *
	 * @param storeCode
	 * @return
	 */
	private Long countStoreActivity(String storeCode) {
		// 获取当月1号，和下月1号
		String startTime = DateUtils.getDateStrByFormat(DateUtils.getFirstDayZeroPointOfMonth(0), DateUtils.DEFAULT_DAY_PATTERN);
		String endTime = DateUtils.getDateStrByFormat(DateUtils.getFirstDayZeroPointOfMonth(1), DateUtils.DEFAULT_DAY_PATTERN);
		Long num = activityDao.countActivityNumPerMonth(storeCode, startTime, endTime);
		if (num != null) {
			return num;
		}
		return 0L;
	}

	private void delActivityKey(String storeCode) {
		// 活动列表
		String activityListKeys = String.format(CacheKeyConstants.MemberExpand.ACTIVITY_LIST, storeCode, 0);
		// 进行中的活动列表
		String activeActivityListKey = String.format(CacheKeyConstants.MemberExpand.ACTIVITY_ACTIVE_LIST, storeCode);

		redisClient.del(activityListKeys);
		redisClient.del(activeActivityListKey);

	}

	/**
	 * 
	 * 根据店员工号，查询其发展的客户详细信息
	 *
	 * @param employeeId
	 */
	public GridViewVo<CustomerDetailVo> queryCustomerDetailByEmployeeId(Long activityId, String employeeId, String source, int pageNo, int pageSize) {
		String key = String.format(CacheKeyConstants.MemberExpand.CUSTOMER_DETAIL_LIST_BY_EMPLOYEE, employeeId, activityId, source, pageNo);
		// query from redis
		TypeToken<GridViewVo<CustomerDetailVo>> typeToken = new TypeToken<GridViewVo<CustomerDetailVo>>() {
		};
		GridViewVo<CustomerDetailVo> viewVo = redisClient.get(key, typeToken.getType());
		if (viewVo != null) {
			return viewVo;
		}
		viewVo = queryCustomerDetailByEmployeeIdAdapter(CustomerDetailVo.class, activityId, employeeId, source, pageNo, pageSize);
		// save to redis
		redisClient.setex(key, CacheKeyConstants.MemberExpand.HOUR_EXPIRE_TIME, viewVo);
		return viewVo;
	}

	/**
	 * 
	 * 根据店员工号，查询其发展的客户详细信息
	 *
	 * @param employeeId
	 */
	public GridViewVo<CustomerDetailWithSaleVo> queryCustomerDetailWithSaleByEmployeeId(Long activityId, String employeeId, String source, int pageNo, int pageSize) {
		String key = String.format(CacheKeyConstants.MemberExpand.CUSTOMER_DETAIL_LIST_WITH_SALE_BY_EMPLOYEE, employeeId, activityId, source, pageNo);
		// query from redis
		TypeToken<GridViewVo<CustomerDetailWithSaleVo>> typeToken = new TypeToken<GridViewVo<CustomerDetailWithSaleVo>>() {
		};
		GridViewVo<CustomerDetailWithSaleVo> viewVo = redisClient.get(key, typeToken.getType());
		if (viewVo != null) {
			return viewVo;
		}
		viewVo = queryCustomerDetailByEmployeeIdAdapter(CustomerDetailWithSaleVo.class, activityId, employeeId, source, pageNo, pageSize);
		// save to redis
		redisClient.setex(key, CacheKeyConstants.MemberExpand.HOUR_EXPIRE_TIME, viewVo);
		return viewVo;
	}

	private <T extends CustomerDetailVo> GridViewVo<T> queryCustomerDetailByEmployeeIdAdapter(Class<T> type, Long activityId, String employeeId, String source, int pageNo, int pageSize) {
		GridViewVo<T> viewVo = new GridViewVo<T>();
		long num = adminActivityDao.countCustomerDetailByEmployeeId(activityId, employeeId, source);
		viewVo.setPageNo((long) pageNo);
		viewVo.setCount(num);
		if (num == 0) {
			return viewVo;
		}

		int start = (pageNo - 1) * pageSize;
		// 查询客户基础信息
		List<T> list = adminActivityDao.queryCustomerDetailByEmployeeId(activityId, employeeId, source, start, pageSize, type);
		if (CollectionUtils.isEmpty(list)) { // 此逻辑理论不会出现
			viewVo.setCount(0l);
			return viewVo;
		}

		// 查询意向品类列表
		queryIntentCate(list);
		// 查询意向品牌列表
		queryIntentCmmdty(list);
		// 查询标签信息
		queryLabelNames(list);

		if (CustomerDetailVo.class.equals(type)) {
			viewVo.setData(list);
			return viewVo;
		}
		// 查询销售信息
		querySaleInfo(list, activityId);
		// 查询外拓地点
		queryPlace(list);
		viewVo.setData(list);
		return viewVo;
	}

	// 查询某门店(某品类?)下所有的客户列表(总部，大区，店长权限（督导）访问)
	public GridViewVo<CustomerDetailVo> queryCustomerDetailByStoreAndCateCode(Long activityId, String storeCode, String cateCode, String source, int pageNo, int pageSize) {
		String key = String.format(CacheKeyConstants.MemberExpand.CUSTOMER_DETAIL_LIST_BY_STORE_CATE, storeCode, cateCode, activityId, source, pageNo);
		// query from redis
		TypeToken<GridViewVo<CustomerDetailVo>> typeToken = new TypeToken<GridViewVo<CustomerDetailVo>>() {
		};
		GridViewVo<CustomerDetailVo> viewVo = redisClient.get(key, typeToken.getType());
		if (viewVo != null) {
			return viewVo;
		}

		viewVo = queryCustomerDetailAdapter(CustomerDetailVo.class, activityId, storeCode, cateCode, source, pageNo, pageSize);
		// save to redis
		redisClient.setex(key, CacheKeyConstants.MemberExpand.HOUR_EXPIRE_TIME, viewVo);
		return viewVo;
	}

	// 查询某门店(某品类?)下所有的客户列表(总部，大区，店长权限（督导）访问)_含其购买信息
	public GridViewVo<CustomerDetailWithSaleVo> queryCustomerDetailWithSaleByStoreAndCateCode(Long activityId, String storeCode, String cateCode, String source, int pageNo, int pageSize) {
		String key = String.format(CacheKeyConstants.MemberExpand.CUSTOMER_DETAIL_LIST_WITH_SALE_BY_STORE_CATE, storeCode, cateCode, activityId, source, pageNo);
		// query from redis
		TypeToken<GridViewVo<CustomerDetailWithSaleVo>> typeToken = new TypeToken<GridViewVo<CustomerDetailWithSaleVo>>() {
		};
		GridViewVo<CustomerDetailWithSaleVo> viewVo = redisClient.get(key, typeToken.getType());
		if (viewVo != null) {
			return viewVo;
		}
		viewVo = queryCustomerDetailAdapter(CustomerDetailWithSaleVo.class, activityId, storeCode, cateCode, source, pageNo, pageSize);
		// save to redis
		redisClient.setex(key, CacheKeyConstants.MemberExpand.HOUR_EXPIRE_TIME, viewVo);
		return viewVo;
	}

	private <T extends CustomerDetailVo> GridViewVo<T> queryCustomerDetailAdapter(Class<T> type, Long activityId, String storeCode, String cateCode, String source, int pageNo, int pageSize) {
		GridViewVo<T> viewVo = new GridViewVo<T>();
		// 查询满足条件的客户又多少，如果为0,则一切over，返回给页面空对象
		long num = adminActivityDao.countCustomerDetailByDZDD(activityId, storeCode, cateCode, source);
		viewVo.setPageNo((long) pageNo);
		viewVo.setCount(num);
		if (num == 0) {
			return viewVo;
		}
		// 查询当前页的数据
		int start = (pageNo - 1) * pageSize;
		List<T> list = adminActivityDao.queryCustomerDetailByDZDD(activityId, storeCode, cateCode, source, start, pageSize, type);
		// 查询意向品类列表
		queryIntentCate(list);
		// 查询意向品牌列表
		queryIntentCmmdty(list);
		// 查询标签信息
		queryLabelNames(list);

		if (CustomerDetailVo.class.equals(type)) {
			viewVo.setData(list);
			return viewVo;
		}
		// 查询销售信息
		querySaleInfo(list, activityId);
		// 查询外拓地点
		queryPlace(list);
		viewVo.setData(list);
		return viewVo;
	}

	/**
	 * 查询意向品类数据
	 *
	 * @param list
	 */
	private void queryIntentCate(List<? extends CustomerDetailVo> list) {
		for (CustomerDetailVo detail : list) {
			List<Map<String, Object>> intents = activityDao.queryIntentCateByCustDetailId(String.valueOf(detail.getDetailId()));
			String intentCates = changeIntentsToString(intents, NumberUtils.INTEGER_ZERO.intValue());
			detail.setIntentCates(intentCates);
		}
	}

	/**
	 * 查询意向商品数据
	 *
	 * @param list
	 */
	private void queryIntentCmmdty(List<? extends CustomerDetailVo> list) {
		for (CustomerDetailVo detail : list) {
			List<Map<String, Object>> intents = activityDao.queryIntentCmmdtyByCustDetailId(String.valueOf(detail.getDetailId()));
			String intentCmmdtys = changeIntentsToString(intents, NumberUtils.INTEGER_ONE.intValue());
			detail.setIntentCmmdtys(intentCmmdtys);
		}
	}

	/**
	 * 
	 * 查询客户关联的标签信息
	 *
	 * @param list
	 */
	private void queryLabelNames(List<? extends CustomerDetailVo> list) {
		for (CustomerDetailVo detail : list) {
			String labelNames = adminActivityDao.queryLabelNamesByCustDetailId(detail.getDetailId());
			if (StringUtils.isEmpty(labelNames)) {
				labelNames = StringUtils.EMPTY;
			}
			detail.setLabelNames(labelNames);
		}
	}

	/**
	 * 意向商品，意向品类转成字符串
	 *
	 * @param intents
	 * @param type
	 *            0:意向品类，1：意向商品
	 * @return
	 */
	private String changeIntentsToString(List<Map<String, Object>> intents, int type) {
		if (CollectionUtils.isEmpty(intents)) {
			return StringUtils.EMPTY;
		}
		StringBuilder result = new StringBuilder();
		if (NumberUtils.INTEGER_ZERO.intValue() == type) { // 意向品类
			for (Map<String, Object> map : intents) {
				String cateName = (String) map.get("cateName");
				String brands = (String) map.get("brands");
				String item = cateName + "　" + brands;
				result.append(item).append(LINE_SEPARATOR);
			}
		} else {// 意向商品
			for (Map<String, Object> map : intents) {
				String cmmdtyName = (String) map.get("cmmdtyName");
				result.append(cmmdtyName).append(LINE_SEPARATOR);
			}
		}
		return result.toString();
	}

	/**
	 * 
	 * 根据手机号或者会员编码 查询他的消费信息
	 *
	 * @param list
	 * @param activityId
	 *            参与的活动
	 */
	private void querySaleInfo(List<? extends CustomerDetailVo> list, Long activityId) {
		String yes = "是", no = "否";
		for (CustomerDetailVo item : list) {
			CustomerDetailWithSaleVo detail = (CustomerDetailWithSaleVo) item;
			String mobile = detail.getMobile();
			String custNo = detail.getCustNo();
			if (StringUtils.isEmpty(mobile)) { // 没有手机号，continue
				detail.setHasSale(no);
				continue;
			}
			List<Map<String, Object>> saleInfoList = adminActivityDao.querySaleInfo(mobile, custNo, activityId);
			String saleInfo = getSaleInfo(saleInfoList);
			if (StringUtils.isEmpty(saleInfo)) {
				detail.setHasSale(no);
			} else {
				detail.setHasSale(yes);
			}
			detail.setSaleInfo(saleInfo);
		}
	}

	/**
	 * 
	 * 查询的saleInfoList转成字符串
	 *
	 * @param saleInfoList
	 * @return
	 */
	private String getSaleInfo(List<Map<String, Object>> saleInfoList) {
		if (CollectionUtils.isEmpty(saleInfoList)) {
			return StringUtils.EMPTY;
		}
		StringBuilder sb = new StringBuilder();
		for (Map<String, Object> item : saleInfoList) {
			String cateCode = (String) item.get("cateCode");
			String brand = (String) item.get("brand");
			Object amount = item.get("amount");
			String amountStr = StringUtils.EMPTY;
			if (amount != null) {
				amountStr = ((BigDecimal) amount).toString();
			}
			String cateName = ConfigConstants.DEFAULT_CATE_MAP.get(cateCode);
			sb.append(cateName).append(":").append(brand).append("　").append(amountStr).append(LINE_SEPARATOR);
		}
		return sb.toString();
	}

	/**
	 * 查询外拓地点信息
	 * 
	 * @param list
	 */
	private void queryPlace(List<? extends CustomerDetailVo> list) {
		for (CustomerDetailVo item : list) {
			CustomerDetailWithSaleVo detail = (CustomerDetailWithSaleVo) item;
			String expandId = detail.getExpandId();
			String place = adminActivityDao.queryPlaceByExpandId(expandId);
			detail.setPlace(place);
		}
	}
}
